package simportal.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import simportal.persistent.User;
import simportal.utils.MD5Util;

import com.cfuture08.eweb4j.orm.dao.factory.DAOFactory;
import com.cfuture08.util.StringUtil;

/**
 * 用户相关业务
 * 
 * @author weiwei
 * 
 */
public class UserService extends BaseService<User> {
	public UserService() {
		super(User.class);
	}

	/**
	 * 检查验证码
	 * 
	 * @param _authCode
	 * @param request
	 * @return
	 */
	public String checkAuCode(String _authCode, HttpServletRequest request) {
		// 系统保存在session中的验证码
		HttpSession session = request.getSession(true);
		String authCode = (String) session
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (authCode == null || !authCode.equalsIgnoreCase(_authCode)) {
			return "验证码错误";
		}

		return null;
	}

	/**
	 * 登陆，将密码MD5加密与数据库比较，并将状态更新为‘在线’，最后保存到session中取
	 * 
	 * @param user
	 * @param session
	 * @return
	 */
	public String login(User user, String _authCode, HttpServletRequest request) {
		// 对用户输入的内容进行过滤，防止SQL注入
		// ToDo

		// 对用户输入的密码进行MD5加密
		user.setPassword(MD5Util.getMD5(user.getPassword()));
		String[] fields = new String[] { "account", "password" };
		List<User> users = DAOFactory.getSearchDAO()
				.searchByExactAndOrderByIdFieldDESC(user, fields, false);
		if (users == null || users.size() > 1) {
			return "账号或密码错误";
		}

		User _user = users.get(0);
		// 修改该用户状态为在线状态,更新登陆时间，登陆IP
		_user.setStatus("在线");
		_user.setLastLoginTime(StringUtil.getNowTime());
		_user.setLastLoginIp(StringUtil.getIpAddr(request));
		_user.setPassword("");
		int rs = DAOFactory.getUpdateDAO().updateByFields(_user,
				new String[] { "status", "lastLoginTime", "lastLoginIp" });
		if (rs == 0) {
			return "数据库错误";

		}
		HttpSession session = request.getSession(true);
		// 保存到session中去
		session.setAttribute("loginUser", _user);

		return null;
	}

	/**
	 * 检查两次输入密码是否一致
	 * 
	 * @param password
	 * @param rePass
	 * @return
	 */
	public String checkPassword(String password, String rePass) {
		if (!password.equals(rePass)) {
			return "两次输入的密码不同";
		}
		return null;
	}

	/**
	 * 创建用户
	 * @param user
	 * @return
	 */
	public String create(User user) {
		String error = null;
		// 插入数据到数据库
		user.setStatus("下线");
		user.setPassword(MD5Util.getMD5(user.getPassword()));
		error = create(user,"account","账号");
		return error;
	}
	
}
